<template>
  <div class="app-container">
    <!-- 搜索和 操作的行为区 -->
    <div class="conduct">
      <el-input v-model="listQuery.keyword" placeholder="角色名称" class="conduct-input">
        <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
      </el-input>
      <el-button class="danger-btn" @click="handleUpdate(-1, 'create')">创建</el-button>
      <el-button class="primary-btn" @click="handleDelmultip">删除</el-button>
    </div>
    <!-- tabs 切换不同角色 -->
    <el-tabs v-model="active_name" type="card" style="border: 1px solid #f99;" @tab-click="handleClickTab">

      <el-tab-pane v-for="item in list_role" :key="item.roleId" :label="item.roleName" :name="item.roleId" :data-roleid="item.roleId">
        <div class="role-tilte">
          <div class="title-item"> <div class="title-icon" /> 角色ID: {{ item.roleName }}</div>
          <div class="title-item"> <div class="title-icon" /> 创建时间: {{ item.createTime }}</div>
          <div class="title-item"> <div class="title-icon" /> 备注: {{ item.roleName }}</div>
        </div>
        {{ role_checked_perms }}
        <div class="role-tree">
          <div class="tree-title"> <div class="title-icon" /> 角色权限 </div>
          <div class="tree-container">
            <el-tree
              :data="item.perm_role"
              show-checkbox
              node-key="menuId"
              :default-expanded-keys="[1, 2, 3, 4]"
              :default-checked-keys="role_checked_perms"
              :props="defaultProps"
            />
          </div>

        </div>
      </el-tab-pane>

    </el-tabs>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog title="创建角色" :visible.sync="dialogFormVisible" width="40%" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色名称:" required>
          <el-input v-model="temp.roleName" type="text" maxlength="18" placeholder="请输入账户名" />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="temp.remark" />
        </el-form-item>
        <el-form-item label="配置权限:" required>
          选择权限
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button class="primary-btn" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center>
      <div class="del-data del-img"><img :src="require('../../assets/img/del.png')" alt=""></div>
      <div class="del-data del-notify">确定对账号进行【删除】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="dialogPvVisible = false">取消</el-button>
        <el-button class="primary-btn" @click="delData">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils' // 解析时间
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { delAdmin, addAdmin, editAdmin, listAdmin, toggleAdmin, listRole, permRole } from '@/api/system'
import { validPass } from '@/utils/validate'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'Role',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!validPass(value)) {
        callback(new Error('8~16位,包含大小写字母和数字, 可以有特殊字符'))
      } else { callback() }
    }

    return {
      multipleSelection: [],
      is_multip: false, // 是否批量删除
      tableKey: 0,
      list: null,
      total: 0, // 总条数
      listLoading: true,
      listQuery: {
        page: 1, // 第几页
        limit: 10, // 每页显示的条数row
        keyword: '' // 搜索关键字
      },
      calendarTypeOptions,
      statusOptions: ['published', 'draft', 'deleted'], // 角色
      temp: {
        id: undefined,
        userName: '',
        password: '',
        status: '',
        role: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      del_id: '',
      del_index: null,
      dialogPvVisible: false,
      rules: {
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      list_role: [], // 获取角色名和角色id的 列表
      active_name: '', // 当前活跃的角色
      login_userId: '', // 当前登录者的  userId
      defaultProps: { // tree 配置项
        children: 'childrenList',
        label: 'name'
      },
      role_checked_perms: [] // 当前角色所拥有的权限
    }
  },
  created() {
    // this.getList()
    this.getListRole() // 获得角色列表
  },
  mounted() {
    this.login_userId = this.$store.getters.userId || window.localStorage.getItem('userId') // 拿到当前登录者的userId
    // this.handleClickTab()
  },
  methods: {
    // tab 接受点击
    handleClickTab(tab, event) {
      this.getRoleMenu(tab.name) // 通过角色Id (即tab.name) 来调用getMenuPerms, 给this.role_checked_perms赋值
    },
    // 通过角色的roleId 获取当前角色的 所具有的权限菜单
    getRoleMenu(role_id) {
      const perms = []
      permRole(role_id).then(res => {
        if (res.data && res.data.length > 0) {
          getMenuPerms(res.data)
          this.role_checked_perms = perms
        } else {
          this.role_checked_perms = []
        }
        console.log(this.role_checked_perms)
      })

      function getMenuPerms(menu) { // 获取的当前菜单所拥有的权限列表, 数组格式
        menu.forEach((item, i) => {
          perms.push(item.menuId)
          if (item.childrenList.length > 0) {
            getMenuPerms(item.childrenList)
          }
        })
      }
    },

    // 获取 table 列表
    getList() {
      this.listLoading = true
      listAdmin(this.listQuery.page, this.listQuery.limit, this.listQuery.keyword).then(res => {
        this.list = res.data.records
        this.total = parseInt(res.data.total)

        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    // 状态值 切换
    changeStatus(id, status) {
      toggleAdmin(id, status).then(res => {
        this.$notify({
          title: '成功',
          message: '状态修改成功',
          type: 'success',
          duration: 4000
        })
        // this.$message({
        //   message: "状态更改成功!",
        //   type: 'success',
        //   duration: 4000,
        //   showClose: true,
        //   center: true,
        // })
        this.getList() // 重新渲染页面
      })
    },
    // 获取角色列表
    getListRole() {
      listRole(1, 49, '').then(res => {
        this.list_role = res.data.records.filter((val, i) => { // 过滤 得到当前登录者 所创建的角色列表
          return val.createUserId == this.login_userId
        })
        const current_logon = this.$store.getters.menulist

        this.list_role.forEach((val, i) => {
          // val.perm_role = current_logon   // 将当前登录者 所具有的权限,存到 角色名和角色id这个列表中
          this.$set(val, 'perm_role', current_logon) // 将当前登录者 所具有的权限,存到 角色名和角色id这个列表中
        })
        if (this.list_role.length > 0) {
          this.active_name = this.list_role[0].roleId // 设置第一个 处于活跃
          this.getRoleMenu(this.list_role[0].roleId) // 页面加载完毕, 给this.role_checked_perms赋初始值
        }
      })
    },
    // 点击了 '编辑' 或添加======================================================
    handleUpdate(row, str) {
      if (str == 'create') this.resetTemp() // 清空
      if (str == 'update') this.temp = Object.assign({}, row) // 克隆一个对象
      this.dialogStatus = str
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑: 确认更新数据
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const cryptograph = this.$sha256(this.temp.password + this.temp.userName)
          editAdmin(this.temp.id, cryptograph, this.temp.roleId, this.temp.status, this.temp.userName).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
            this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 确认添加了一个管理员
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const cryptograph = this.$sha256(this.temp.password + this.temp.userName)
          // let data2 = Object.assign({}, this.temp)   // 克隆一个对象

          addAdmin(cryptograph, this.temp.roleId, this.temp.status, this.temp.userName).then(() => {
            // this.list.unshift(this.temp)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 清空temp
    resetTemp() {
      this.temp = {
        id: undefined,
        userName: '',
        password: '',
        status: '',
        role: ''
      }
    },
    // 点击了删除===============================================
    handleDelete(row, index) {
      this.is_multip = false
      this.del_id = row.id
      this.del_index = index
      this.dialogPvVisible = true
    },
    // 点击了 批量删除
    handleDelmultip() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '没有被选中项!',
          type: 'error',
          duration: 4000,
          showClose: true,
          center: true
        })
      } else {
        this.is_multip = true
        this.dialogPvVisible = true
      }
    },
    // 确认了删除
    delData() {
      let ids = []
      if (this.is_multip) { // 批量删
        this.multipleSelection.forEach((item, i) => {
          ids.push(item.id)
        })
        ids = this.multipleSelection
      } else {
        ids = [this.del_id]
      }
      delAdmin(ids).then(() => {
        this.dialogPvVisible = false
        this.list.splice(this.del_index, 1)
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 4000
        })
      })
    },

    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style lang="scss" scoped>
  $theme_text: #0F8BFD;
  $backg:rgba(0,0,0,0);
  $deep_text: #5E5E5E;

  .app-container {
    // background-color: #f99 !important;
    .conduct {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 9;
      width:50%;
      display: flex;
      justify-content: space-between;
      .conduct-input {
        margin-right: 10px;
        border: 0;
        input {
          background: transparent;
          border: 0;
          -webkit-appearance: none;
          border-radius: 0px;
          padding: 12px 5px 12px 15px;
          color: $deep_text;
          // height: 47px;
          caret-color: $deep_text;

          &:-webkit-autofill {
            box-shadow: 0 0 0 1000px $backg inset !important;
            -webkit-text-fill-color: $deep_text !important;
          }
        }
        .el-button {
          color: #fff;
          background-color: #0F8CFD;
        }
      }
    }
    .el-tabs {
      background-color: #fff;
      .role-tilte {
        padding: 0 20px;
        display: flex;
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid #EAEBF0;
        .title-item {
          margin-right: 60px;
        }
      }
      .title-icon {
        display: inline-block;
        background-color: $theme_text;
        width: 4px;
        height: 20px;
        border-radius: 2px;
        transform: translateY(5px);
      }

      .role-tree {
        padding: 0 20px;
        .tree-title {
          display: inline-block;
          // background-color: blueviolet;
        }
        .tree-container {
          display: inline-flex;
          flex-direction: column;
          background-color: antiquewhite;
        }
      }
    }

    .el-dialog {
      .del-data {
        text-align: center;
        margin-bottom: 16px;
        img {
          width: 110px;
          height: 110px;
        }
      }
      .del-img {}
      // min-width: 490px !important;
      // .el-input {
      //   width: 100%;
      //   background-color: blueviolet;
      // }
    }
  }
</style>
